#!/usr/bin/env python
# -*- coding:utf-8 -*-

__author__ = 'WONSORK'


import cgi
import os
import logging
import urllib


from google.appengine.api import images
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers
from google.appengine.ext.webapp.blobstore_handlers import BlobstoreUploadHandler
from google.appengine.ext.webapp import template

from com.crayon.product.ProductUploadBasehandler import ProductUploadHandler
from com.crayon.data.DataStore import Album
from com.crayon.data.DataStore import Picture
from com.crayon.data.DataStore import Product
from com.crayon.data.DataStore import Book


import wsgiref.handlers


#os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from google.appengine.dist import use_library
#use_library('django', '1.1')
#use_library()

# Makes the tags defined by templatetags/basetags.py usable
# by templates rendered in this file
template.register_template_library('templatetags.basetags')




class ImageSharingBaseHandler(webapp.RequestHandler):
  """Base Image Sharing RequestHandlers with some convenience functions."""

  def template_path(self, filename):
    """Returns the full path for a template from its path relative to here."""
#    return os.path.join(os.path.dirname(__file__), filename)
    path = os.path.join(os.path.dirname(__file__), 'templates')
    logging.debug("#######################")
    logging.debug("#######################")
    logging.debug("#######################")
    logging.debug("#######################")
    logging.debug(path)
    return  os.path.join(path,filename)

    
  def render_to_response(self, filename, template_args):
    """Renders a Django template and sends it to the client.

    Args:
      filename: template path (relative to this file)
      template_args: argument dict for the template
    """

    logging.debug("#######################")
    template_args.setdefault('current_uri', self.request.uri)
    logging.debug("#######################")
    logging.debug(self.request.uri)
    logging.debug("#######################")
    
    self.response.out.write(
        template.render(self.template_path(filename), template_args)
    )


class ImageSharingAlbumIndex(ImageSharingBaseHandler):
  """Handler for listing albums."""

  def get(self):
    """Lists all available albums."""
    logging.debug("######################")
    logging.info("##ImageSharingAlbumIndex######################")
    albums = Album.all().order('-created_date')
    self.render_to_response('index.html', {
        'albums': albums,
      })


class ImageSharingAlbumCreate(ImageSharingBaseHandler):
  """Handler for creating a new Album via form."""

  def get(self):
    """Displays the album creation form."""
    self.render_to_response('new.html', {})

  def post(self):
    """Processes an album creation request."""
    Album(name=cgi.escape(self.request.get('albumname')),
          creator=users.get_current_user()).put()
    self.redirect('/')

PICTURES_PER_ROW = 5

class ImageSharingAlbumView(ImageSharingBaseHandler):
  """Handler for viewing the pictures in a particular album."""
  def get(self, album_key):
    """Displays a single album.
    Note that in this and later handlers, the args come
    from a capturing group in the WSGIApplication specification.
    See the webapp framework docs for more info.
    Args:
      album_key: the datastore key for the Album to view.
    """
    album = db.get(album_key)
    pics = []
    num_results = 0

    for picture in album.pictures:
      if num_results % PICTURES_PER_ROW == 0:
        current_row = []
        pics.append(current_row)

      current_row.append(picture)
      
      num_results += 1

    self.render_to_response('album.html', {
        'num_results': num_results,
        'album_key': album.key(),
        'pics': pics,
        'album_name': album.name
      })


class ImageSharingUploadImage(ImageSharingBaseHandler):
  """Handler for uploading images."""

  def get(self, album_key):
    """Display the image upload form.

    Args:
      album_key: datastore key for the album to upload the image to
    """
    album = db.get(album_key)
    self.render_to_response('upload.html', {
        'album_key': album.key(),
        'album_name': album.name
      })

  def post(self, album_key):
    """Process the image upload form.

    We also generate the thumbnail for the picture at this point.

    Args:
      album_key: datastore key for the album to add the image to
    """
    album = db.get(album_key)
    if album is None:
      self.error(400)
      self.response.out.write('Couldn\'t find specified album')

    title = cgi.escape(self.request.get('title'))
    writter = cgi.escape(self.request.get('writter'))
    caption = cgi.escape(self.request.get('caption'))
    category = cgi.escape(self.request.get('category'))
    
    tags = cgi.escape(self.request.get('tags')).split(',')
    tags = [tag.strip() for tag in tags]
    # Get the actual data for the picture
    
    img_data = self.request.POST.get('picfile').file.read()

    try:
      img = images.Image(img_data)
      # Basically, we just want to make sure it's a PNG
      # since we don't have a good way to determine image type
      # through the API, but the API throws an exception
      # if you don't do any transforms, so go ahead and use im_feeling_lucky.
      img.im_feeling_lucky()
      png_data = img.execute_transforms(images.PNG)
      img.resize(60, 100)
      thumbnail_data = img.execute_transforms(images.PNG)
      Picture(submitter=users.get_current_user(),
              title=title,
              writter=writter,
              caption=caption,
              category=category,
              album=album,
              tags=tags,
              data=png_data,
              thumbnail_data=thumbnail_data).put()
      self.redirect('/album/%s' % album.key())
    except images.BadImageError:
      self.error(400)
      self.response.out.write(
          'Sorry, we had a problem processing the image provided.')
    except images.NotImageError:
      self.error(400)
      self.response.out.write(
          'Sorry, we don\'t recognize that image format.'
          'We can process JPEG, GIF, PNG, BMP, TIFF, and ICO files.')
    except images.LargeImageError:
      self.error(400)
      self.response.out.write(
          'Sorry, the image provided was too large for us to process.')



from google.appengine.ext.webapp.util import run_wsgi_app
 
class ImageSharingShowImage(ImageSharingBaseHandler):
  """Handler for viewing a single image.
  Note that this doesn't actually serve the picture, only the page
  containing it. That happens in ImageSharingServeImage.
  """
  def get(self, pic_key):
    """Renders the page for a single picture.
    Args:
      pic_key: key for the Picture model for the picture to display
    """
    bookupload_url = blobstore.create_upload_url('/bookupload')
#    bookupload_url=blobstore.create_upload_url('/show_image')
#    slow_operation()
#    bookupload_url = upload_url_rpc.get_result()
    logging.info("###############URLE#######")
    logging.info(bookupload_url)
    pic = db.get(pic_key)
    count=0
    for book in pic.books:
        logging.info(count)
        count+=1
        logging.info(book.picture.key)
#        logging.info(book.blobkey.key())
        data = book.blobkey
        logging.info("blobkey fine %s" % data.key())
        b = blobstore.BlobInfo.get(data.key())
        logging.info("\t\t%s" % str(b.key()) )
        self.response.out.write('<li><a href="/download/%s' % str(b.key()) + '">' + str(b.filename) + '</a>')

        
        
#    for b in blobstore.BlobInfo.all():
##        logging.info(str(b.filename))
#        logging.info("\t\t%s" % str(b.key()) )
#        self.response.out.write('<li><a href="/download/%s' % str(b.key()) + '">' + str(b.filename) + '</a>')

    
    
    self.render_to_response('show_image.html', {
         'pic': pic
        ,'image_key': pic.key()
        ,'bookupload_url':bookupload_url
        ,'pic_key':pic_key
    })
  
  def post(self):
      logging.info("#######POST")

class BookUploadHandler(blobstore_handlers.BlobstoreUploadHandler):
  def post(self):
      
    upload_files = self.get_uploads('bookfile')  # 'file' is file upload field in the form
    blob_info = upload_files[0]
    
    pic_key = cgi.escape(self.request.get('pic_key'))
    logging.info("pic_key")
    logging.info(pic_key)
    
    pic = db.get(pic_key)

    logging.info(">>>>BLOB_INFO.KEY value")
    logging.info(blob_info.key())

    try :
        Book(submitter=users.get_current_user(),
              picture = pic,
              blobkey = blob_info
              ).put()
        self.redirect('/show_image/%s' % pic_key)
    except :
      self.error(400)
      self.response.out.write(
          'Sorry, we had a problem processing the image provided.')

    
    
#    self.redirect('/serve/%s' % blob_info.key())

class ImageSharingServeImage(webapp.RequestHandler):
  """Handler for dynamically serving an image from the datastore.

  Very simple - it just pulls the appropriate data out of the datastore
  and serves it.
  """

  def get(self, display_type, pic_key):
    """Dynamically serves a PNG image from the datastore.

    Args:
      type: a string describing the type of image to serve (image or thumbnail)
      pic_key: the key for a Picture model that holds the image
    """
    image = db.get(pic_key)

    if display_type == 'image':
      self.response.headers['Content-Type'] = 'image/png'
      self.response.out.write(image.data)
    elif display_type == 'thumbnail':
      self.response.headers['Content-Type'] = 'image/png'
      self.response.out.write(image.thumbnail_data)
    else:
      self.error(500)
      self.response.out.write(
          'Couldn\'t determine what type of image to serve.')

class ImageSharingSearch(ImageSharingBaseHandler):
  """Handler for searching pictures by tag."""

  def get(self):
    """Displays the tag search box and possibly a list of results."""
    query = cgi.escape(self.request.get('q'))
    pics = []
    if query:
      # ListProperty magically does want we want: search for the occurrence
      # of the term in any of the tags.
      pics = Picture.all().filter('tags =', query)
    else:
      query = ''
    self.render_to_response('search.html', {
        'query': query,
        'pics': pics,
      })



class ProductDownloadHandler(blobstore_handlers.BlobstoreDownloadHandler):
    def get(self,blob_key):
        blob_key = str(urllib.unquote(blob_key))
        if not blobstore.get(blob_key):
            self.error(404)
        else:
            self.send_blob(blobstore.BlobInfo.get(blob_key), save_as=True)


class StoreFeedXML(ImageSharingBaseHandler):
  """Handler for viewing the pictures in a particular album."""
  def get(self, album_key):
    album = db.get(album_key)
    pics = []
    num_results = 0
    for picture in album.pictures:
      pics.append(picture)
      num_results += 1

    self.render_to_response('atom.xml', {
        'num_results': num_results
        ,'album_key': album.key()
        ,'album_name': album.name
        ,'pics': pics,
      })



def main():
  URLS = [('/', ImageSharingAlbumIndex),
             ('/bookupload',BookUploadHandler),
             ('/download/([^/]+)?', ProductDownloadHandler),
             ('/new', ImageSharingAlbumCreate),
             ('/album/([-\w]+)', ImageSharingAlbumView),
             ('/upload/([-\w]+)', ImageSharingUploadImage),
             ('/show_image/([-\w]+)', ImageSharingShowImage),
             ('/(thumbnail|image)/([-\w]+)', ImageSharingServeImage),
             ('/storefeed/([-\w]+)', StoreFeedXML),
             ('/search', ImageSharingSearch)
             ]
  application = webapp.WSGIApplication(URLS,debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
  main()
